package com.yang.util;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 音频工具类
 * 作者： yang
 * 时间： 2025/07/08
 */
@Slf4j
@RequiredArgsConstructor
public class AudioUtil {

    // 音频保存路径
    private static final String AUDIO_SAVE_DIR = "src/main/resources/static/audio";

    /**
     * 创建音频文件处理器
     *
     * @return 音频文件处理器
     * @throws IOException 如果创建文件失败
     */
    public static AudioFileHandler createAudioFile() throws IOException {
        // 确保目录存在
        ensureDirectoryExists();

        // 生成唯一文件名 (时间戳 + UUID)
        String audioFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"))
                + "_" + UUID.randomUUID().toString().substring(0, 8) + ".wav";

        // 创建临时文件
        File audioFile = new File(AUDIO_SAVE_DIR + "/" + audioFileName);
        FileOutputStream audioOutputStream = new FileOutputStream(audioFile);

        log.info("创建音频文件: {}", audioFile.getAbsolutePath());

        return new AudioFileHandler(audioFile, audioOutputStream, audioFileName);
    }

    /**
     * 确保目录存在
     */
    private static void ensureDirectoryExists() {
        File directory = new File(AUDIO_SAVE_DIR);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    /**
     * 音频文件处理器
     */
    public static class AudioFileHandler {
        private final File audioFile;
        private final FileOutputStream outputStream;
        private final FileChannel channel;
        private final String fileName;

        public AudioFileHandler(File audioFile, FileOutputStream outputStream, String fileName) {
            this.audioFile = audioFile;
            this.outputStream = outputStream;
            this.channel = outputStream.getChannel();
            this.fileName = fileName;
        }

        /**
         * 写入音频数据
         *
         * @param byteBuffer 音频数据
         * @throws IOException 如果写入失败
         */
        public void writeData(ByteBuffer byteBuffer) throws IOException {
            // 将 ByteBuffer 中的数据写入文件通道
            channel.write(byteBuffer);
        }

        /**
         * 关闭音频文件
         */
        public void close() {
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    log.error("关闭文件通道失败", e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                    log.info("音频文件保存成功: {}", audioFile.getAbsolutePath());
                } catch (IOException e) {
                    log.error("关闭音频输出流失败", e);
                }
            }
        }

        /**
         * 获取文件路径
         *
         * @return 文件路径
         */
        public String getFilePath() {
            return AUDIO_SAVE_DIR + "/" + fileName;
        }
    }
}
